﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;

namespace Domain.UserManagement.Entities
{
    public class Password
    {
        private string _hashedPassword;

        public string HashedPassword 
        { 
            get
            {
                return _hashedPassword;
            } 
            
            set 
            { 
                if (value == null)
                {
                    return;
                }
                _hashedPassword = value;        
            } 
        }


        public bool ChangePassword(string newPassword)
        {
            if (IsPasswordLegal(newPassword))
            {
                HashedPassword = HashPassword(newPassword);
                return true;
            }

            return false;
        }

        private string HashPassword(string password)
        {
            return FormsAuthentication.HashPasswordForStoringInConfigFile(password, "sha1");
        }

        private bool IsPasswordLegal(string password)
        {
            if (!ContainsDigit(password) || password.Any(passwordChar => IsIllegalCharacter(passwordChar)) || !IsLegalLength(password))
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private bool ContainsDigit(string password)
        {
            return password.Any(passwordChar => IsDigit(passwordChar));
        }

        private bool IsDigit(char passwordChar)
        {
            return passwordChar >= '0' && passwordChar <= '9';
        }

        private bool IsIllegalCharacter(char passwordChar)
        {
            var testChar = Convert.ToInt16(passwordChar);
            return testChar < 33 || testChar > 122;
        }

        private bool IsLegalLength(string password)
        {
            if (password.Length >= 5 && password.Length <= 50)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
